package com.sz.app.oss.api.system;

import com.sz.app.oss.constants.MessagesCodes;
import com.sz.app.oss.constants.Permissions;
import com.sz.app.oss.exception.ErrorCodes;
import com.sz.biz.app.web.BaseController;
import com.sz.common.base.dto.ResultDto;
import com.sz.common.base.dto.TreeNode;
import com.sz.common.base.exception.BizException;
import com.sz.common.base.exception.Exceptions;
import com.sz.common.core.system.dto.OrgDto;
import com.sz.common.core.system.dto.UserOrgRelDto;
import com.sz.common.core.system.service.OrgService;
import com.sz.app.oss.api.system.dto.OrgNodeDragDto;
import io.swagger.annotations.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.util.List;

/**
 * Function: UserGroupController <br>
 * Author: wentao.chang <br>
 * Date: 2016-11-16 10:22:13
 */
@RestController
@RequestMapping("${api}/sys/usergroups")
@Api(description = " ", tags = "002_2、用户组管理")
public class UserGroupController extends BaseController {

    @Autowired
    private OrgService orgsService;


    /**
     * 按Id查询一个用户组
     *
     * @throws BizException   biz
     * @throws ParseException par
     */
    @ApiOperation(value = "根据id获取用户组", notes = "-")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orgid", value = "用户组的id ",
                    required = true, dataType = "int", paramType = "path")})
    @RequestMapping(value = "/{orgid}", method = {RequestMethod.GET})
//    @RequiresPermissions(value = {Permissions.SYS_MGT_UGROUP})
    public ResultDto findById(@PathVariable("orgid") int orgid) throws BizException, ParseException {
        OrgDto org = orgsService.findById(2, orgid);
        ResultDto dto = new ResultDto();
        dto.setData(org);
        return dto;
    }

    /**
     * 给某个用户组新建一个用户组
     *
     * @throws Exception e
     */
    @ApiOperation(value = "新建一个用户组", notes = "-<br>权限：" + Permissions.SYS_MGT_UGROUP)
    @ApiImplicitParams({@ApiImplicitParam(name = "orgDto", value = "需要的参数：parentId,name\r\n"
            + "shortName,code,description", required = true, paramType = "OrgDto")})
    @RequestMapping(value = "", method = {RequestMethod.POST})
    @RequiresPermissions(value = {Permissions.SYS_MGT_UGROUP})
    public ResultDto saveOrg(@RequestBody OrgDto orgDto) throws Exception {
        int orgId = orgsService.saveOrg(2, orgDto);
        ResultDto dto = getSaveSuccessDto(MessagesCodes.MODULE_USER_GROUP);
        dto.setData(orgId);
        return dto;
    }

    /**
     * 修改一个用户组
     *
     * @throws Exception e
     */
    @ApiOperation(value = "修改一个用户组", notes = "-<br>权限：" + Permissions.SYS_MGT_UGROUP)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orgid", value = "用户组的id ",
                    required = true, dataType = "int", paramType = "path"),
            @ApiImplicitParam(name = "orgDto", value = "需要的参数：orgName,orgShortName,\r\n"
                    + "orgCode,description,parentId",
                    required = true, paramType = "com.sz.common.core.system.dto.OrgDto")})
    @RequestMapping(value = "/{orgid}", method = {RequestMethod.PUT})
    @RequiresPermissions(value = {Permissions.SYS_MGT_UGROUP})
    public ResultDto updateOrg(@PathVariable int orgid, @RequestBody OrgDto orgDto) throws Exception {
        orgsService.updateOrg(2, orgid, orgDto);
        ResultDto dto = getUpdateSuccessDto(MessagesCodes.MODULE_USER_GROUP);
        dto.setData(orgid);
        return dto;
    }

    /**
     * 获取指定用户组的树 可指定关键字查询
     *
     * @throws BizException   biz
     * @throws ParseException par
     */
    @ApiOperation(value = "获取指定用户组的树 可指定关键字查询", notes = "-")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "q", value = "用户组查询关键字 默认空",
                    dataType = "string", paramType = "query")})
    @RequestMapping(value = "/tree", method = {RequestMethod.GET})
    //@RequiresPermissions(value = {Permissions.SYS_MGT_UGROUP})
    public ResultDto getOrgTreeBy2(@RequestParam(required = false, defaultValue = "") String q)
            throws BizException, ParseException {
        List<TreeNode> orgs = orgsService.getOrgTreeByOrgGroupId(2, q);
        ResultDto dto = new ResultDto();
        dto.setData(orgs);
        return dto;
    }

    /**
     * 获取指定用户组机构的列表 可指定关键字查询
     *
     * @throws BizException   biz
     * @throws ParseException par
     */
    @ApiOperation(value = "获取指定用户组机构的列表 可指定关键字查询", notes = "-")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "q", value = "用户组查询关键字 默认空",
                    dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "porgid", value = "父组织的id 在此父组织下查询  默认0 查询所有",
                    dataType = "int", paramType = "query")})
    @RequestMapping(value = "", method = {RequestMethod.GET})
    //@RequiresPermissions(value = {Permissions.SYS_MGT_UGROUP})
    public ResultDto getOrgListByUserOrgGroupId(
            @RequestParam(required = false, defaultValue = "") String q,
            @RequestParam(required = false, defaultValue = "0") int porgid) throws BizException, ParseException {
        List<OrgDto> orgs = orgsService.getOrgListByOrgGroupId(2, q, porgid);
        ResultDto dto = new ResultDto();
        dto.setData(orgs);
        return dto;
    }

    /**
     * 获取指定级别的子节点
     *
     * @throws BizException   biz
     * @throws ParseException par
     */
    @ApiOperation(value = "获取指定级别的子节点", notes = "-")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "parentid", value = "用户组的父节点id,加载根节点parentid为0",
                    required = true, dataType = "int", paramType = "path")})
    @RequestMapping(value = "/subnode/{parentid}", method = {RequestMethod.GET})
    //@RequiresPermissions(value = {Permissions.SYS_MGT_UGROUP})
    public ResultDto getOrgSubNodeByParentId(@PathVariable int parentid)
            throws BizException, ParseException {
        List<TreeNode> orgs = orgsService.getSubOrgDtos(2, parentid);
        ResultDto dto = new ResultDto();
        dto.setData(orgs);
        return dto;
    }

    /**
     * 拖动用户组
     *
     * @throws BizException   biz
     * @throws ParseException par
     */
    @ApiOperation(value = "拖动用户组", notes = "-<br>权限：" + Permissions.SYS_MGT_UGROUP)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orgid", value = "拖动用户组的id",
                    required = true, dataType = "int", paramType = "path"),
            @ApiImplicitParam(name = "dto", value = "拖动对象{targetparentid,targetpreid}",
                    required = true, dataType = "OrgNodeDragDto", paramType = "body")})
    @RequestMapping(value = "/drag/{orgid}", method = {RequestMethod.PUT})
    @RequiresPermissions(value = {Permissions.SYS_MGT_UGROUP})
    public ResultDto dragOrgTreeNode(@PathVariable int orgid, @RequestBody OrgNodeDragDto dto)
            throws BizException, ParseException {
        if (dto.getTargetpreid() == null) {
            throw Exceptions.bizException(ErrorCodes.ERROR_COMMON, "请检查组织！");
        }
        orgsService.dragOrgTree(2, orgid, dto.getTargetparentid(), dto.getTargetpreid());
        ResultDto rdto = getOperateSuccessDto(MessagesCodes.USERGROUP_DRAG_SUCCESS);
        rdto.setData(orgid);
        return rdto;
    }


    /**
     * 用户组上移下移
     *
     * @throws BizException   biz
     * @throws ParseException par
     */
    @ApiOperation(value = "用户组上移下移", notes = "-<br>权限：" + Permissions.SYS_MGT_UGROUP)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orgid", value = "移动用户组的id",
                    required = true, dataType = "int", paramType = "path"),
            @ApiImplicitParam(name = "direct", value = "移动方向:-1向上移动 1向下移动",
                    required = true, dataType = "int", paramType = "query")})
    @RequestMapping(value = "/shift/{orgid}", method = {RequestMethod.PUT})
    @RequiresPermissions(value = {Permissions.SYS_MGT_UGROUP})
    public ResultDto shiftOrgTreeNode(@PathVariable int orgid, @RequestParam("direct") int direct)
            throws BizException, ParseException {
        if (Math.abs(direct) != 1) {
            throw Exceptions.bizException(ErrorCodes.ERROR_MODEL_ORG_SHIFT_DIRECT_ERR);
        }
        orgsService.shiftOrgTreeNode(2, orgid, direct);
        ResultDto dto = getOperateSuccessDto(MessagesCodes.USERGROUP_SHIFT_SUCCESS);
        dto.setData(orgid);
        return dto;
    }

    @ApiOperation(value = "用户组删除", notes = "删除该用户组后，该用户组下所有子用户组、用户、角色也被删除。<br>权限：" + Permissions.SYS_MGT_UGROUP)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orgid", value = "删除用户组的id",
                    required = true, dataType = "int", paramType = "path")})
    @RequestMapping(value = "/{orgid}", method = {RequestMethod.DELETE})
    @RequiresPermissions(value = {Permissions.SYS_MGT_UGROUP})
    public ResultDto deleteOrgTreeNode(@PathVariable int orgid)
            throws Exception {
        orgsService.deleteOrgTreeNode(2, orgid);
        ResultDto dto = getDeleteSuccessDto(MessagesCodes.MODULE_USER_GROUP);
        dto.setData(orgid);
        return dto;
    }

    /**
     * 用户组分配角色
     *
     * @throws BizException   biz
     * @throws ParseException par
     */
    @ApiOperation(value = "用户组分配角色", notes = "用户组分配角色<br>权限：" + Permissions.SYS_MGT_UGROUP)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orgid", value = "分配用户组的id",
                    required = true, dataType = "int", paramType = "path"),
            @ApiImplicitParam(name = "roleIds", value = "角色的id列表字符串,用','分割",
                    required = true, dataType = "string", paramType = "body")})
    @RequestMapping(value = "/{orgid}/assignrole", method = {RequestMethod.PUT})
    @RequiresPermissions(value = {Permissions.SYS_MGT_UGROUP})
    public ResultDto assignOrgRoles(@PathVariable int orgid, @RequestBody String roleIds)
            throws BizException, ParseException {
        orgsService.assignOrgRoles(2, orgid, roleIds);
        ResultDto dto = getOperateSuccessDto(MessagesCodes.USERGROUP_SHIFT_SUCCESS);
        dto.setData(orgid);
        return dto;
    }

    /**
     * 用户组删除角色
     *
     * @throws BizException   biz
     * @throws ParseException par
     */
    @ApiOperation(value = "用户组删除角色", notes = "用户组删除角色<br>权限：" + Permissions.SYS_MGT_UGROUP)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orgId", value = "删除用户组的id",
                    required = true, dataType = "int", paramType = "path"),
            @ApiImplicitParam(name = "roleId", value = "角色的id",
                    required = true, dataType = "int", paramType = "path")})
    @RequestMapping(value = "/{orgId}/removerole/{roleId}", method = {RequestMethod.DELETE})
    @RequiresPermissions(value = {Permissions.SYS_MGT_UGROUP})
    public ResultDto removeOrgRole(@PathVariable int orgId, @PathVariable int roleId)
            throws BizException, ParseException {
        orgsService.removeOrgRole(2, orgId, roleId);
        ResultDto dto = getDeleteSuccessDto(MessagesCodes.MODULE_USER_GROUP);
        dto.setData(orgId);
        return dto;
    }

    /**
     * 用户组分配成员
     *
     * @throws BizException   biz
     * @throws ParseException par
     */
    @ApiOperation(value = "用户组分配用户 增量", notes = "用户组分配用户<br>权限：" + Permissions.SYS_MGT_UGROUP)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orgid", value = "用户组的id",
                    required = true, dataType = "int", paramType = "path"),
            @ApiImplicitParam(name = "userIds", value = "用户的id列表,增量更新,\r\n不删除已有用户",
                    required = true, dataType = "string", paramType = "body")})
    @RequestMapping(value = "/{orgid}/assignuser", method = {RequestMethod.PUT})
    @RequiresPermissions(value = {Permissions.SYS_MGT_UGROUP})
    public ResultDto assignOrgUserIds(@PathVariable int orgid, @RequestBody List<Integer> userIds)
            throws BizException, ParseException {
        orgsService.assignOrgUsers(2, orgid, userIds);
        ResultDto dto = getOperateSuccessDto(MessagesCodes.USERGROUP_ASSIGN_USERS_SUCCESS);
        dto.setData(orgid);
        return dto;
    }

    /**
     * 用户组删除用户
     */
    @ApiOperation(value = "用户组删除用户", notes = "用户组删除用户<br>权限：" + Permissions.SYS_MGT_UGROUP)
    @RequestMapping(value = "/removeuser", method = {RequestMethod.PUT})
    @RequiresPermissions(value = {Permissions.SYS_MGT_UGROUP})
    public ResultDto removeOrgUsers(@RequestBody @ApiParam List<UserOrgRelDto> userOrgs) {
        orgsService.removeOrgUsers(2, userOrgs);
        ResultDto dto = getOperateSuccessDto(MessagesCodes.USERGROUP_REMOVE_USERS_SUCCESS);
        dto.setData(0);
        return dto;
    }

    /**
     * 异步校验编码
     */
    @ApiOperation(value = "异步校验编码", notes = "异步校验编码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "编码",
                    required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "userGroupId", value = "用户组id 修改时传id 新增时传空",
                    dataType = "int", paramType = "query")})
    @RequestMapping(value = "/checkcode", method = {RequestMethod.GET})
    //@RequiresPermissions(value = {Permissions.SYS_MGT_UGROUP})
    public ResultDto orgCodeCheck(@RequestParam String code,
                                  @RequestParam(required = false, defaultValue = "0") int userGroupId) {
        orgsService.orgCodeCheck(2, userGroupId, code);
        return new ResultDto();
    }

    /**
     * 异步校验名称
     */
    @ApiOperation(value = "异步校验名称", notes = "异步校验名称")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "名称",
                    required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "parentId", value = "parentId",
                    required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "userGroupId", value = "用户组id 修改时传id 新增时传空",
                    dataType = "int", paramType = "query")})
    @RequestMapping(value = "/checkname", method = {RequestMethod.GET})
    //@RequiresPermissions(value = {Permissions.SYS_MGT_UGROUP})
    public ResultDto orgNameCheck(@RequestParam String name, @RequestParam int parentId,
                                  @RequestParam(required = false, defaultValue = "0") int userGroupId) {
        orgsService.orgNameCheck(2, parentId, userGroupId, name);
        return new ResultDto();
    }

    /**
     * 异步校验简称
     */
    @ApiOperation(value = "异步校验简称", notes = "异步校验简称")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "shortName", value = "简称",
                    required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "parentId", value = "parentId",
                    required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "userGroupId", value = "用户组id 修改时传id 新增时传空",
                    dataType = "int", paramType = "query")})
    @RequestMapping(value = "/checkshortname", method = {RequestMethod.GET})
    //@RequiresPermissions(value = {Permissions.SYS_MGT_UGROUP})
    public ResultDto orgShortNameCheck(@RequestParam String shortName, @RequestParam int parentId,
                                       @RequestParam(required = false, defaultValue = "0") int userGroupId) {
        orgsService.orgShortNameCheck(2, parentId, userGroupId, shortName);
        return new ResultDto();
    }
}
